package cn.tx.redis7.service;

import cn.tx.redis7.config.CheckUtils;
import cn.tx.redis7.domain.TUser;
import cn.tx.redis7.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author jizenan
 * @date 2025/6/4
 * Description:
 */
@Service
@Slf4j
public class UserService {

    public static final String CACHA_KEY_CUSTOMER = "customer:";

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    
    @Autowired
    private CheckUtils checkUtils;

    //写操作
    public void addCustomer(TUser tUser){
        int i = userMapper.insert(tUser);
        if(i>0){
            //mysql插入成功，需要重新查询一次将数据捞出来，写进redis
            TUser result = userMapper.selectById(tUser);
            //redis缓存key
            String key = CACHA_KEY_CUSTOMER+tUser.getId();
            //捞出来的数据写进redis
            redisTemplate.opsForValue().set(key,result);
        }
    }

    public TUser findUserById(Integer id){
        TUser tUser = null;
        //缓存redis的key
        String key = CACHA_KEY_CUSTOMER+id;

        //1.先去查redis
        tUser = (TUser)redisTemplate.opsForValue().get(key);

        //2.redis有直接返回，没有再去查数据库
        if(tUser == null){
            //3.查mysql
            tUser = userMapper.selectById(id);
            //3.1mysql有，redis无
            if(tUser != null){
                //3.2mysql数据写会redis
                redisTemplate.opsForValue().set(key,tUser);
            }
        }
        return tUser;
    }

    /**
     * bloomFilter -> redis -> mysql
     * 白名单：whitelistCustomer
     * */
    public TUser findCustomerByIdWithBloomFilter(Integer id){
        TUser tUser = null;
        //缓存redis的key
        String key = CACHA_KEY_CUSTOMER+id;

        //布隆过滤器check：无是绝对无，有是可能有
        //======================================
        if(!checkUtils.checkWithBloomFilter("whitelistCustomer", key)){
            log.info("白名单无此用户，不可以访问",key);
            return null;
        }
        //======================================
        //1.先去查redis
        tUser = (TUser)redisTemplate.opsForValue().get(key);

        //2.redis有直接返回，没有再去查数据库
        if(tUser == null){
            //3.查mysql
            tUser = userMapper.selectById(id);
            //3.1mysql有，redis无
            if(tUser != null){
                //3.2mysql数据写会redis
                redisTemplate.opsForValue().set(key,tUser);
            }
        }
        return tUser;
    }
}
